﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Data;
using System.Data.SqlClient;

using SIPO.Library;
using SIPO.Library.DomainObject.Administration.Catalog;
using SIPO.Library.Enum;
using SIPO.Library.Interfaces;

namespace SIPO.Library.DataAccess.Administration.Catalog
{
    public partial class recDayOffRepo : IRepository<recDayOff, int>
    {
        public object SelectScalar(SQL.Function.Aggregate function, string column,string parameters)
        {
            object _result = null;
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    StringBuilder sbQuery = new StringBuilder();
                    switch (function)
                    {
                        case SQL.Function.Aggregate.Max:
                            sbQuery.AppendFormat("SELECT MAX({0}) FROM master.recDayOff", column,parameters);
                            break;
                        case SQL.Function.Aggregate.Min:
                            sbQuery.AppendFormat("SELECT MIN({0}) FROM master.recDayOff", column,parameters);
                            break;
                        case SQL.Function.Aggregate.Distinct:
                            sbQuery.AppendFormat("SELECT DISTINCT({0}) FROM master.recDayOff", column,parameters);
                            break;
                        case SQL.Function.Aggregate.Count:
                            sbQuery.AppendFormat("SELECT COUNT({0}) FROM master.recDayOff", column,parameters);
                            break;
                        case SQL.Function.Aggregate.Sum:
                            sbQuery.AppendFormat("SELECT SUM({0}) FROM master.recDayOff", column,parameters);
                            break;
                        case SQL.Function.Aggregate.Avg:
                            sbQuery.AppendFormat("SELECT AVG({0}) FROM master.recDayOff", column,parameters);
                            break;
                        default:
                            // do nothing 
                            break;
                    }

                    cmd.CommandText = sbQuery.ToString();
                    cmd.CommandType = CommandType.Text;
                    try
                    {
                        conn.Open();
                        _result = cmd.ExecuteScalar();
                    }
                    catch (Exception ex)
                    {
                        throw (ex);
                    }
                    finally
                    {
                        if (conn.State == ConnectionState.Open) conn.Close();
                    }
                }
            }
            return _result;
        }

        public recDayOff GetByDayOffDate(DateTime dayoffdate)
        {
            recDayOff t = null;
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = "SELECT DayOffID, DayOffYear, DayOffDate, Remark, CreatedDate, CreatedBy, UpdatedDate, UpdatedBy FROM master.recDayOff WHERE DayOffDate = @DayOffDate";
                    cmd.CommandType = CommandType.Text;
                    cmd.Parameters.Add("@DayOffDate", SqlDbType.DateTime).Value = dayoffdate;
                    try
                    {
                        conn.Open();
                        using (SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                        {
                            while (dr.Read())
                            {
                                t = new recDayOff();
                                t.DayOffID = dr[recDayOff.Fields.DayOffID] == DBNull.Value ? 0 : int.Parse(dr[recDayOff.Fields.DayOffID].ToString());
                                t.DayOffYear = dr[recDayOff.Fields.DayOffYear] == DBNull.Value ? (short)0 : short.Parse(dr[recDayOff.Fields.DayOffYear].ToString());
                                t.DayOffDate = dr[recDayOff.Fields.DayOffDate] == DBNull.Value ? DateTime.Now : DateTime.Parse(dr[recDayOff.Fields.DayOffDate].ToString());
                                t.Remark = dr[recDayOff.Fields.Remark] == DBNull.Value ? string.Empty : dr[recDayOff.Fields.Remark].ToString();
                                t.CreatedDate = dr[recDayOff.Fields.CreatedDate] == DBNull.Value ? (DateTime?)null : DateTime.Parse(dr[recDayOff.Fields.CreatedDate].ToString());
                                t.CreatedBy = dr[recDayOff.Fields.CreatedBy] == DBNull.Value ? string.Empty : dr[recDayOff.Fields.CreatedBy].ToString();
                                t.UpdatedDate = dr[recDayOff.Fields.UpdatedDate] == DBNull.Value ? (DateTime?)null : DateTime.Parse(dr[recDayOff.Fields.UpdatedDate].ToString());
                                t.UpdatedBy = dr[recDayOff.Fields.UpdatedBy] == DBNull.Value ? string.Empty : dr[recDayOff.Fields.UpdatedBy].ToString();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        throw (ex);
                    }
                    finally
                    {
                        if (conn.State == ConnectionState.Open) conn.Close();
                    }
                }
            }
            return t;
        }

        public List<recDayOff> GetDataByYear(int year)
        {
            List<recDayOff> tt = new List<recDayOff>();
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = "SELECT DayOffID, DayOffYear, DayOffDate, Remark, CreatedDate, CreatedBy, UpdatedDate, UpdatedBy FROM master.recDayOff WHERE DayOffYear=@DayOffYear";
                    cmd.Parameters.Add("@DayOffYear", SqlDbType.Int).Value = year;
                    cmd.CommandType = CommandType.Text;
                    try
                    {
                        conn.Open();
                        using (SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                        {
                            while (dr.Read())
                            {
                                recDayOff t = new recDayOff();
                                t.DayOffID = dr[recDayOff.Fields.DayOffID] == DBNull.Value ? 0 : int.Parse(dr[recDayOff.Fields.DayOffID].ToString());
                                t.DayOffYear = dr[recDayOff.Fields.DayOffYear] == DBNull.Value ? (short)0 : short.Parse(dr[recDayOff.Fields.DayOffYear].ToString());
                                t.DayOffDate = dr[recDayOff.Fields.DayOffDate] == DBNull.Value ? DateTime.Now : DateTime.Parse(dr[recDayOff.Fields.DayOffDate].ToString());
                                t.Remark = dr[recDayOff.Fields.Remark] == DBNull.Value ? string.Empty : dr[recDayOff.Fields.Remark].ToString();
                                t.CreatedDate = dr[recDayOff.Fields.CreatedDate] == DBNull.Value ? (DateTime?)null : DateTime.Parse(dr[recDayOff.Fields.CreatedDate].ToString());
                                t.CreatedBy = dr[recDayOff.Fields.CreatedBy] == DBNull.Value ? string.Empty : dr[recDayOff.Fields.CreatedBy].ToString();
                                t.UpdatedDate = dr[recDayOff.Fields.UpdatedDate] == DBNull.Value ? (DateTime?)null : DateTime.Parse(dr[recDayOff.Fields.UpdatedDate].ToString());
                                t.UpdatedBy = dr[recDayOff.Fields.UpdatedBy] == DBNull.Value ? string.Empty : dr[recDayOff.Fields.UpdatedBy].ToString();
                                tt.Add(t);
                                t.Dispose();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        throw (ex);
                    }
                    finally
                    {
                        if (conn.State == ConnectionState.Open) conn.Close();
                    }
                }
            }
            return tt;
        }

        public List<recDayOff> GetList(int pageSize, int currentPage, string sortName, string sortOrder,string parameters)
        {
            List<recDayOff> tt = new List<recDayOff>();
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    int startRow = ((currentPage - 1) * pageSize) + 1;
                    int endRow = (startRow + pageSize);

                    StringBuilder sbQuery = new StringBuilder();
                    sbQuery.AppendFormat(" WITH result_set AS ");
                    sbQuery.AppendFormat(" ( ");
                    sbQuery.AppendFormat("    SELECT ");
                    sbQuery.AppendFormat("      ROW_NUMBER() OVER (ORDER BY {0} {1}) AS [row_number], ", sortName, sortOrder);
                    sbQuery.AppendFormat("      DayOffID, DayOffYear, DayOffDate, Remark, CreatedDate, CreatedBy, UpdatedDate, UpdatedBy ");
                    sbQuery.AppendFormat("    FROM ");
                    sbQuery.AppendFormat("      master.recDayOff ");
                    sbQuery.AppendFormat("      {0}",parameters);
                    sbQuery.AppendFormat(" ) ");
                    sbQuery.AppendFormat(" SELECT * FROM result_set WHERE [row_number] BETWEEN {0} AND {1} ", startRow, endRow);

                    cmd.CommandText = sbQuery.ToString();
                    cmd.CommandType = CommandType.Text;
                    try
                    {
                        conn.Open();
                        using (SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                        {
                            while (dr.Read())
                            {
                                recDayOff t = new recDayOff();
                                t.DayOffID = dr[recDayOff.Fields.DayOffID] == DBNull.Value ? 0 : int.Parse(dr[recDayOff.Fields.DayOffID].ToString());
                                t.DayOffYear = dr[recDayOff.Fields.DayOffYear] == DBNull.Value ? (short)0 : short.Parse(dr[recDayOff.Fields.DayOffYear].ToString());
                                t.DayOffDate = dr[recDayOff.Fields.DayOffDate] == DBNull.Value ? DateTime.Now : DateTime.Parse(dr[recDayOff.Fields.DayOffDate].ToString());
                                t.Remark = dr[recDayOff.Fields.Remark] == DBNull.Value ? string.Empty : dr[recDayOff.Fields.Remark].ToString();
                                t.CreatedDate = dr[recDayOff.Fields.CreatedDate] == DBNull.Value ? (DateTime?)null : DateTime.Parse(dr[recDayOff.Fields.CreatedDate].ToString());
                                t.CreatedBy = dr[recDayOff.Fields.CreatedBy] == DBNull.Value ? string.Empty : dr[recDayOff.Fields.CreatedBy].ToString();
                                t.UpdatedDate = dr[recDayOff.Fields.UpdatedDate] == DBNull.Value ? (DateTime?)null : DateTime.Parse(dr[recDayOff.Fields.UpdatedDate].ToString());
                                t.UpdatedBy = dr[recDayOff.Fields.UpdatedBy] == DBNull.Value ? string.Empty : dr[recDayOff.Fields.UpdatedBy].ToString();
                                tt.Add(t);
                                t.Dispose();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        throw (ex);
                    }
                    finally
                    {
                        if (conn.State == ConnectionState.Open) conn.Close();
                    }
                }
            }
            return tt;
        }

        public bool CheckDataByCode(int dayoffyear,DateTime dayoffdate)
        {
            bool _result = false;
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    StringBuilder sbQuery = new StringBuilder();

                    sbQuery.AppendFormat("SELECT COUNT(DayOffYear) DayOffYear FROM master.recDayOff WHERE DayOffYear=@DayOffYear AND DayOffDate=@DayOffDate");
                    cmd.Parameters.Add("@DayOffYear", SqlDbType.SmallInt).Value = dayoffyear;
                    cmd.Parameters.Add("@DayOffDate", SqlDbType.Date).Value = dayoffdate;

                    cmd.CommandText = sbQuery.ToString();
                    cmd.CommandType = CommandType.Text;

                    try
                    {
                        conn.Open();

                        var objId = cmd.ExecuteScalar();
                        objId = objId == DBNull.Value ? 0 : int.Parse(objId.ToString());

                        _result = int.Parse(objId.ToString()) == 0 ? false : true;

                    }
                    catch (Exception ex)
                    {
                        throw (ex);
                    }
                    finally
                    {
                        if (conn.State == ConnectionState.Open) conn.Close();
                    }
                }
            }
            return _result;
        }

        public DateTime GetDueDate(string date)
        {
            SqlConnection conn = new SqlConnection(connectionString);
            SqlCommand cmd = new SqlCommand("SELECT dbo.FN_CekDueDate(@Param1) DueDate", conn);
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.Add("@Param1", SqlDbType.VarChar).Value = date;
            try
            {
                conn.Open();
                return Convert.ToDateTime(cmd.ExecuteScalar());
            }
            catch (Exception ex)
            {
                throw (ex);
            }
            finally
            {
                if (conn.State == ConnectionState.Open) conn.Close();
            }

        }

        public DateTime GetDueDateForIuranBerkala()
        {
            SqlConnection conn = new SqlConnection(connectionString);
            string sql = @" SELECT  top 1 dbo.FN_CekDueDate (cast(year(getdate()) as varchar(4))+SUBSTRING([Value],3,2)+SUBSTRING([Value],1,2))    
								 FROM [master].[recParameter]
					            WHERE ParameterCode LIKE 'IURAN%'
					              and cast(DATEPART(year, getdate()) as nvarchar)+SUBSTRING([Value],3,2)+SUBSTRING([Value],1,2) >= 
						              CONVERT(VARCHAR, getdate(), 112)";
            SqlCommand cmd = new SqlCommand(sql, conn);
            cmd.CommandType = CommandType.Text;
            try
            {
                conn.Open();
                return Convert.ToDateTime(cmd.ExecuteScalar());
            }
            catch (Exception ex)
            {
                throw (ex);
            }
            finally
            {
                if (conn.State == ConnectionState.Open) conn.Close();
            }

        }

        public DateTime GetCurrentDateFromRecParameter()
        {
            SqlConnection conn = new SqlConnection(connectionString);
            SqlCommand cmd = new SqlCommand("SELECT dbo.getdateServer() CurrentDate", conn);
            cmd.CommandType = CommandType.Text;            
            try
            {
                conn.Open();
                return Convert.ToDateTime(cmd.ExecuteScalar());
            }
            catch (Exception ex)
            {
                throw (ex);
            }
            finally
            {
                if (conn.State == ConnectionState.Open) conn.Close();
            }

        }
    }
}
